<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8" />
  <title>心电数据详情 - 设备 {{ device.device_id }}</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <script src="https://cdn.plot.ly/plotly-2.27.0.min.js"></script>
</head>

<body class="bg-gray-100 font-sans min-h-screen">
  <div class="p-6 max-w-6xl mx-auto">
    <!-- 顶部栏 -->
    <div class="flex justify-between items-center mb-6">
      <h1 class="text-2xl font-semibold text-blue-700">📈 设备 {{ device.device_id }} 的心电数据</h1>
      <button id="backBtn" class="bg-gray-500 text-white px-4 py-2 rounded hover:bg-gray-600">返回</button>
    </div>

    <!-- 无数据提示 -->
    <div id="noData" class="hidden text-center text-gray-600 text-lg bg-white py-10 rounded-lg border border-gray-200 shadow-sm">
      🚫 该设备暂无数据
    </div>

    <!-- 心电图 -->
    <div id="ecgChart" class="w-full h-[480px]"></div>

    <!-- 心电记录信息 -->
    <div class="mt-4">
      <h3 class="text-xl font-semibold">心电记录信息</h3>
      <p><strong>开始时间：</strong> {{ ecg_record.start_time }}</p>
      <p><strong>结束时间：</strong> {{ ecg_record.end_time or "暂无结束时间" }}</p>
      <p><strong>数据长度：</strong> {{ ecg_record.data.split(',').length }} 数据点</p>
    </div>
  </div>

  <script>
    window.addEventListener("DOMContentLoaded", () => {
      const dataArr = `{{ ecg_record.data | tojson | safe }}`.split(',').map(v => parseFloat(v)).filter(v => !isNaN(v));
      const startTime = new Date(`{{ ecg_record.start_time }}`);
      const timeArr = dataArr.map((_, i) => new Date(startTime.getTime() + (i / 250) * 1000)); // 假设采样率为250Hz

      // 绘制心电波形图
      const trace = {
        x: timeArr,
        y: dataArr,
        mode: "lines",
        line: { color: "rgb(16,185,129)", width: 1 },
        hoverinfo: "x+y",
        name: "心电信号"
      };

      const layout = {
        margin: { l: 60, r: 30, t: 20, b: 50 },
        xaxis: {
          title: "时间",
          type: "date",
          tickformat: "%H:%M:%S",
          showgrid: true
        },
        yaxis: {
          title: "电压 (mV)",
          range: [-1, 1],
          showgrid: true
        },
        dragmode: "pan"
      };

      Plotly.newPlot("ecgChart", [trace], layout, {
        responsive: true,
        displaylogo: false,
        scrollZoom: true
      });
    });
  </script>
</body>
</html>
